package com.chanjiedata.changbs.module.mine;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chanjiedata.changbs.R;
import com.chanjiedata.changbs.base.BaseFragment;
import com.chanjiedata.changbs.base.MainApplication;
import com.chanjiedata.changbs.bean.ServiceBean;
import com.chanjiedata.changbs.bean.UserBean;
import com.chanjiedata.changbs.help.GlideHelper;
import com.chanjiedata.changbs.help.UserHelper;
import com.chanjiedata.changbs.module.main.MyMachineActivity;
import com.chanjiedata.changbs.module.main.PartnerActivity;
import com.chanjiedata.changbs.net.Apis;
import com.chanjiedata.changbs.net.NetworkManager;
import com.chanjiedata.changbs.net.WebApis;
import com.chanjiedata.changbs.net.interfaces.OnRequestCallBack;
import com.chanjiedata.changbs.proto.Index;
import com.chanjiedata.changbs.proto.MemberOuterClass;
import com.chanjiedata.changbs.utlis.StringUtil;
import com.chanjiedata.changbs.utlis.ValidateUtils;
import com.chanjiedata.changbs.view.MineItemLayout;
import com.chanjiedata.changbs.web.ui.WebViewActivity;
import com.example.havi.helper.ChatHelper;
import com.example.havi.interfaces.LoginCallBack;
import com.example.havi.ui.ChatActivity;
import com.google.protobuf.InvalidProtocolBufferException;
import com.ruffian.library.widget.RTextView;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by Administrator on 2018/2/2 0002.
 */

public class MineFragment extends BaseFragment {
    Unbinder unbinder;
    @BindView(R.id.mine_iv_head_icon)
    ImageView mineIvHeadIcon;
    @BindView(R.id.mine_iv_head_setting)
    ImageView mineIvHeadSetting;
    @BindView(R.id.mine_tv_level)
    RTextView mineTvLevel;
    @BindView(R.id.tv_head_phone)
    TextView tvHeadPhone;
    @BindView(R.id.mine_tv_username)
    TextView mineTvUsername;
    @BindView(R.id.mine_tv_id)
    TextView mineTvId;
    @BindView(R.id.tv_jifen_text)
    TextView tvJifenText;
    @BindView(R.id.mine_tv_ji_fen)
    TextView mineTvJiFen;
    @BindView(R.id.ll_count)
    LinearLayout llCount;
    @BindView(R.id.ll_qu_dao)
    ImageView llQuDao;
    @BindView(R.id.ll_ji_ju)
    LinearLayout llJiJu;
    @BindView(R.id.ll_ye_wu)
    LinearLayout llYeWu;
    @BindView(R.id.mine_mil_one)
    MineItemLayout mineMilOne;
    @BindView(R.id.mine_mil_two)
    MineItemLayout mineMilTwo;
    @BindView(R.id.mine_mil_three)
    MineItemLayout mineMilThree;
    @BindView(R.id.mine_mil_four)
    MineItemLayout mineMilFour;
    @BindView(R.id.mine_mil_five)
    MineItemLayout mineMilFive;
    @BindView(R.id.mine_mil_six)
    MineItemLayout mineMilSix;


    private UserBean userInfoBean;



    @Override
    protected int getLayoutId() {
        return R.layout.fragment_mine;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    protected void initView() {
        if (UserHelper.isLogin()) {
            userInfoBean = UserHelper.getUser();
            loadUserData();
        }

    }

    private void refreshUI(UserBean userInfoBean) {
        mineTvUsername.setText(userInfoBean.getTruename());
        GlideHelper.INSTANCE.loadCircleImage(mineIvHeadIcon, userInfoBean.getMember_avatar());
        if (userInfoBean.getMember_level() == 1) {  // 青铜会员
            mineTvLevel.setText("青铜会员");
        } else if (userInfoBean.getMember_level() == 2) {  // 白银会员
            mineTvLevel.setText("白银会员");
        } else if (userInfoBean.getMember_level() == 3) {  // 黄金会员
            mineTvLevel.setText("黄金会员");
        } else if (userInfoBean.getMember_level() == 4) {  // 白金会员
            mineTvLevel.setText("白金会员");
        } else if (userInfoBean.getMember_level() == 5) {  // 砖石会员
            mineTvLevel.setText("砖石会员");
        }
        tvHeadPhone.setText(StringUtil.PhoneToPass(userInfoBean.getMember_mobile()));
//        tvGongShi.setText(userInfoBean.getMember_name());
        mineTvId.setText("ID：" + userInfoBean.getMember_id());
        mineTvJiFen.setText(userInfoBean.getMember_points() + "");
    }

    @Override
    protected void init() {
    }

    /**
     * 项目中维护个人信息 只用一个UserBean ,调用个人信息 后同步本地个人信息
     */
    private void loadUserData() {
        NetworkManager.INSTANCE.post(Apis.memberDataInfo, new OnRequestCallBack() {
            @Override
            public void onOk(byte[] bytes) throws InvalidProtocolBufferException {
                MemberOuterClass.Member member = MemberOuterClass.Member.parseFrom(bytes);
                userInfoBean = new UserBean();
                userInfoBean.setMember_id(member.getMemberId());
                userInfoBean.setMember_name(member.getMemberName());
                userInfoBean.setMember_mobile(member.getMemberMobile());
                userInfoBean.setMember_avatar(member.getMemberAvatar());
                userInfoBean.setMember_level(member.getMemberLevel());
                userInfoBean.setIs_bank(member.getIsBank());
                userInfoBean.setIs_approve(member.getIsApprove());
                userInfoBean.setIs_paypwd(member.getIsPaypwd());
                userInfoBean.setTruename(member.getTruename());
                userInfoBean.setIdcard(member.getIdcard());
                userInfoBean.setAge(member.getEvolution().getAge());
                userInfoBean.setSex(member.getEvolution().getSex());
                userInfoBean.setEvolution_city(member.getEvolution().getEvolutionCity());
                userInfoBean.setEvolution_address(member.getEvolution().getEvolutionAddress());
                userInfoBean.setEvolution_city_id(member.getEvolution().getEvolutionCityId());
                UserHelper.syncCurrentUserInfo(userInfoBean);   //同步个人信息
                refreshUI(userInfoBean);
            }

            @Override
            public void onError(int code, String errorMessage) {

            }
        });

//         加载客服数据
        NetworkManager.INSTANCE.post(Apis.get_kfu_info, new OnRequestCallBack() {
            @Override
            public void onOk(byte[] response)  throws  InvalidProtocolBufferException{
                Index.get_kfu_info kefu_message =  Index.get_kfu_info.parseFrom(response);
                ServiceBean serviceBean = new ServiceBean();
                serviceBean.setMember_id(kefu_message.getMemberId());
                serviceBean.setMember_name(kefu_message.getMemberName());
                serviceBean.setMember_mobile(kefu_message.getMemberMobile());
                serviceBean.setMember_avatar(kefu_message.getMemberAvatar());
                serviceBean.setChat_id(kefu_message.getChatId());
                serviceBean.setChat_pwd(kefu_message.getChatPwd());
                UserHelper.saveKeFuUserInfo(serviceBean);
            }

            @Override
            public void onError(int errorCode, String errorMessage) {

            }
        });
    }


    @Override
    public void onResume() {
        super.onResume();
        if (mineIvHeadIcon != null) {
            if (UserHelper.isLogin()) {
                userInfoBean = UserHelper.getUser();
                loadUserData();
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @OnClick({R.id.mine_iv_head_icon, R.id.mine_iv_head_setting, R.id.ll_count, R.id.ll_qu_dao, R.id.ll_ji_ju,
            R.id.ll_ye_wu, R.id.mine_mil_one, R.id.mine_mil_two, R.id.mine_mil_three, R.id.mine_mil_four,
            R.id.mine_mil_five, R.id.mine_mil_six,R.id.iv_edit_user_info})
    public void onViewClicked(View view) {
        //  需要实名认证才能使用功能
        if (UserHelper.getUser().getIs_approve() == 0) {
            showToast("请先实名认证");
            startActivity(RenZhenActivity.class);
            return;
        }
        switch (view.getId()) {
            case R.id.mine_iv_head_icon:
            case R.id.iv_edit_user_info:
                startActivity(EditUserInfoActivity.class);
                break;
            case R.id.mine_iv_head_setting:
                startActivityForResult(SettingActivity.class, 200);
                break;
            case R.id.ll_count:
                startActivity(EarningDetailActivity.class);
                break;
            case R.id.ll_qu_dao:
                startActivity(PartnerActivity.class);
                break;
            case R.id.ll_ji_ju:
                startActivity(MyMachineActivity.class);
                break;
            case R.id.ll_ye_wu:
                WebViewActivity.startActivity(mContext, WebApis.Business_application);
                break;
            case R.id.mine_mil_one:
                startActivity(BankCardActivity.class);
                break;
            case R.id.mine_mil_two:
                startActivity(MessageActivity.class);
                break;
            case R.id.mine_mil_three:
//                startActivity(JiFenLogActivity.class);
                break;
            case R.id.mine_mil_four:
                startActivity(AlreadyActivity.class);
                break;
            case R.id.mine_mil_five:
                startActivity(PolicyActivity.class);
                break;
            case R.id.mine_mil_six:
                startChat();
                break;
        }
    }
    private void startChat() {
        boolean login = ChatHelper.getInstance().isLogin();
        if (login) {
            // 打开客服聊天
            ServiceBean keFuInfo = UserHelper.getKeFuInfo();
            if (ValidateUtils.isValidate(keFuInfo)) {
                ChatActivity.startActivity(mContext, keFuInfo.getMember_id() + "", keFuInfo.getMember_name(), keFuInfo.getMember_avatar(), keFuInfo.getChat_id(), keFuInfo.getMember_mobile());
            } else {
                showToast("暂无客服信息");
            }
        } else {
            showToast("聊天登录中");
            MainApplication.getChatHelper().login(UserHelper.getUser().getChat_id(), UserHelper.getUser().getChat_pwd(), new LoginCallBack() {
                @Override
                public void onSuccess() {
                    //判断是否为客服
                    // 打开客服聊天
                    ServiceBean keFuInfo = UserHelper.getKeFuInfo();
                    if (ValidateUtils.isValidate(keFuInfo)) {
                        mContext.runOnUiThread(() -> showToast("人工客服回复时间：工作日9:00-12:00；13:30-18:00"));
                        ChatActivity.startActivity(mContext, keFuInfo.getMember_id() + "", keFuInfo.getMember_name(), keFuInfo.getMember_avatar(), keFuInfo.getChat_id(), keFuInfo.getMember_mobile());
                    } else {
                        mContext.runOnUiThread(() -> showToast("暂无客服信息"));
                    }
                }

                @Override
                public void onError(int code, String message) {
                    mContext.runOnUiThread(() -> showToast("聊天暂时登录失败"));
                }
            });
        }
    }
}
